package com.fh.web.controller;

import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fh.dto.PubDdv;
import com.fh.dto.SysUser;
import com.fh.web.constants.FhManagerConstant;
import com.fh.web.constants.GlobalConstants;
import com.fh.web.service.CustomService;
import com.fh.web.service.PurviewService;
import com.fh.web.vo.PurviewVo;
import com.fh.web.vo.ShowTreeVo;

/**
 * 权限点管理control
 * @author admin
 *
 */
@Controller
@RequestMapping("purview")
public class PurviewController {
	private final Logger LOGGER = LoggerFactory.getLogger(getClass());
	
	@Resource
	private CustomService customService;
	
	@Resource
	private PurviewService purviewService;
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("manager")
	private ModelAndView manager(HttpServletRequest request,HttpServletResponse response) {
			// 申明返回页面参数map
			Map<String, Object> resMap = new HashMap<String, Object>();
			String pId = request.getParameter("id");
			try {
				// 查询用户是否登录
				SysUser staff = (SysUser) request.getSession().getAttribute(GlobalConstants.SYS_USER);
				if (staff != null) {
					// 查询用户操作权限
					resMap = customService.userCanOperation(staff, pId);
					resMap.put("resCode", FhManagerConstant.RST_SUCCESS);
				} else {
					resMap.put("resCode", FhManagerConstant.RST_FAIL);
				}
			} catch (Exception e) {
				resMap.put("resCode", FhManagerConstant.RST_FAIL);
				LOGGER.error("权限点管理页面异常", e);
			}
			return new ModelAndView("/purview/pueViewList", resMap);
		}
	
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getPurviewAndOperation", method = {
			RequestMethod.GET, RequestMethod.POST })
	private List<ShowTreeVo> getPurviewAndOperation(HttpServletRequest request,
			HttpServletResponse response) {
		// 申明easyUi前台显示树参数
		List<ShowTreeVo> treeList = new ArrayList<ShowTreeVo>();
		try {
			// 查询所有权限点和操作
			List<PurviewVo> purviewList = purviewService.getPurviewAndOperation();
			if ((purviewList != null) && (purviewList.size() > 0)) {
				for (PurviewVo r : purviewList) {
					// 申明树节点实例
					ShowTreeVo tree = new ShowTreeVo();
					// 封装树节点参数
					tree.setId(r.getPurId().toString());
					// 判断节点是否有父节点
					if (r.getParentPurId() != null && !"".equals(r.getParentPurId())) {
						tree.setPid(r.getParentPurId().toString());
					} else {
						tree.setState("closed");
					}
					tree.setText(r.getPurName());
					tree.setIconCls(r.getIcon());
					tree.setUrl(r.getPurValue());
					tree.setpType(r.getPurType().toString());
					treeList.add(tree);
				}
			}
		} catch (Exception e) {
			LOGGER.error("查询所有权限点和操作异常", e);
			return null;
		}
		return treeList;
	}
	
	/**
	 * 进入编辑页面
	 * 
	 * @param request
	 * @param response
	 */

	@RequestMapping(value = "/goEditPurView", method = { RequestMethod.GET,
			RequestMethod.POST })
	private ModelAndView goEditPurView(HttpServletRequest request,
			HttpServletResponse response) {
		// 申明返回页面参数map
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			String pId = request.getParameter("id");
			// 根据id查询权限点
			PurviewVo purviewVo = purviewService.selectPurviewById(pId);
			resMap.put("purView", purviewVo);
		} catch (Exception e) {
			LOGGER.error("跳转权限点编辑页面异常", e);
		}
		return new ModelAndView("purview/purViewEdit", resMap);
	}

	/**
	 * 编辑权限点 mod by yq @ 2016/7/27
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */

	@RequestMapping(value = "/editPurView", method = { RequestMethod.GET,
			RequestMethod.POST })
	private void editPurView(@ModelAttribute PurviewVo purviewVo,
			HttpServletResponse response) throws Exception {
		// 申明easyUi页面返回对象
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		try {
			// 判断权限点标记是否重复
			if (purviewService.getPurviewByCode(purviewVo)) {
				out.print("权限点编码已存在");
			} else if(purviewService.getPurviewByName(purviewVo)){
				out.print("同级菜单下权限点名称已存在");
			}else{
				purviewVo.setPurName(this.changeCharset(purviewVo.getPurName(), "UTF-8"));
				purviewService.editPurView(purviewVo);
				out.print("修改成功");
			}
		} catch (Exception e) {
			out.print("修改失败");
			LOGGER.error("编辑权限点异常", e);
		}
	}
	
	/*
	 * 删除节点信息
	 */
	@ResponseBody
	@RequestMapping(value = "/delPurview", method = { RequestMethod.GET,
			RequestMethod.POST })
	private PurviewVo delPurview(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		PurviewVo purviewVo = new PurviewVo();
		String id = request.getParameter("id");
		try {
			if(1==purviewService.isExcit(Long.parseLong(id))){
				purviewVo.setState(1);
				return purviewVo;
			}else{
				// 删除节点信息
				purviewService.delPurview(Long.parseLong(id));
				purviewVo.setState(0);
				return purviewVo;
			}
			
		} catch (Exception e) {
			// 异常返回状态-1
			LOGGER.error("删除角色异常", e);
			purviewVo.setState(-1);
			return purviewVo;
		}
	}
	
	/**
	 * 进入添加权限点页面
	 * 
	 * @param request
	 * @param response
	 */

	@RequestMapping(value = "/goAddPurView", method = { RequestMethod.GET,
			RequestMethod.POST })
	private ModelAndView goAddPurView(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			String pId = request.getParameter("id");
			// 根据id查询权限点
			List<PubDdv> purTypes = purviewService.purTypes();
			resMap.put("purTypes", purTypes);
		} catch (Exception e) {
			LOGGER.error("跳转权限点添加页面异常", e);
		}
		return new ModelAndView("purview/purViewAdd",resMap);
	}

	/**
	 * 添加权限点 mod by yq @ 2016/7/27
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */

	@RequestMapping(value = "/addPurView", method = { RequestMethod.GET,
			RequestMethod.POST })
	private void AddPurView(@ModelAttribute PurviewVo purviewVo,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 申明easyUi页面返回对象
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		try {
			// 从session获取用户信息
			SysUser sysStaff = (SysUser) request.getSession().getAttribute(
					"userObj");
			// 查询判断权限点编码是否重复
			if (purviewService.getPurviewByCode(purviewVo)) {
				out.print("权限点编码已存在");
			}else if(purviewService.getPurviewByName(purviewVo)){
				out.print("同级菜单下权限点名称已存在");
			}else {
				purviewVo.setPurName(this.changeCharset(purviewVo.getPurName(), "UTF-8"));
				purviewService.addPurview(purviewVo, sysStaff);
				out.print("添加成功");
			}
		} catch (Exception e) {
			out.print("添加失败");
			LOGGER.error("添加权限点异常", e);
		}
	}
	
	/**
	   * 查询所有权限点
	   * 
	   * @param request
	   * @param response
	   * @return
	   */
	  @ResponseBody
	  @RequestMapping(value = "/getTreeNoChild", method = {RequestMethod.GET, RequestMethod.POST})
	  private List<ShowTreeVo> getTreeNoChild(HttpServletRequest request,
	      HttpServletResponse response) {
	    // 申明easyUi前台显示树参数
	    List<ShowTreeVo> treeList = new ArrayList<ShowTreeVo>();
	    try {
	      // 获取前台请求参数
	      // 权限点父节点id
	      String pId = request.getParameter("pId");
	      // 查询父节点下所有权限点数据
	      List<PurviewVo> purviewList = purviewService.getPurviewListNoChild(pId);

	      if ((purviewList != null) && (purviewList.size() > 0)) {
	        for (PurviewVo r : purviewList) {
	          // 申明树节点实例
	          ShowTreeVo tree = new ShowTreeVo();
	          // 设置树节点参数
	          tree.setId(r.getPurId().toString());
	          // 判断设置节点的父节点id
	          if (r.getParentPurId() != null && !"".equals(r.getParentPurId())) {
	            tree.setPid(r.getParentPurId().toString());
	          } else {
	            tree.setState("closed");
	          }
	          tree.setState("closed");
	          // 判断父节点是否有子节点
	          int childNum = purviewService.getPurviewListByid(Long.valueOf(r.getPurId().toString()));
	          if (childNum == 0)
	            tree.setState("open");
	          tree.setText(r.getPurName());
	          tree.setIconCls(r.getIcon());
	          Map<String, Object> attr = new HashMap<String, Object>();
	          attr.put("url", r.getPurValue());
	          tree.setAttributes(attr);
	          treeList.add(tree);
	        }
	      }
	    } catch (Exception e) {
	      LOGGER.error("查询所有子权限点", e);
	      return null;
	    }
	    return treeList;
	  }
	  
	  /**
	   * 查询所有权限点
	   * 
	   * @param request
	   * @param response
	   * @return
	   */
	  @ResponseBody
	  @RequestMapping(value = "/getTree", method = {RequestMethod.GET, RequestMethod.POST})
	  private List<ShowTreeVo> getTree(HttpServletRequest request, HttpServletResponse response) {
	    // 申明easyUi前台显示树参数
	    List<ShowTreeVo> treeList = new ArrayList<ShowTreeVo>();
	    try {
	      // 查询所有的权限点
	      List<PurviewVo> purviewList = purviewService.getAllPurviewList1();
	      if ((purviewList != null) && (purviewList.size() > 0)) {
	        for (PurviewVo r : purviewList) {
	          // 申明树节点实例
	          ShowTreeVo tree = new ShowTreeVo();
	          // 设置树节点参数
	          tree.setId(r.getPurId().toString());
	          // 设置节点父节点id
	          if (r.getParentPurId() != null && !"".equals(r.getParentPurId())) {
	            tree.setPid(r.getParentPurId().toString());
	          } else {
	            tree.setState("closed");
	          }
	          tree.setState("closed");
	          // 判断父节点是否有子节点
	          int num = purviewService.getPurviewListByid((long)r.getPurId());
	          if (num == 0)
	            tree.setState("open");
	          tree.setText(r.getPurName());
	          tree.setIconCls(r.getIcon());
	          Map<String, Object> attr = new HashMap<String, Object>();
	          attr.put("url", r.getPurValue());
	          tree.setAttributes(attr);
	          treeList.add(tree);
	        }
	      }
	    } catch (Exception e) {
	      LOGGER.error("查询所有权限点异常", e);
	      return null;
	    }
	    return treeList;
	  }
	  
	  /** 
	      * 字符串编码转换的实现方法 
	      * @param str  待转换编码的字符串 
	      * @param newCharset 目标编码 
	      * @return 
	      * @throws UnsupportedEncodingException 
	      */  
	     public String changeCharset(String str, String newCharset)  
	       throws UnsupportedEncodingException {  
	      if (str != null) {  
	       //用默认字符编码解码字符串。  
	       byte[] bs = str.getBytes("ISO-8859-1");  
	       //用新的字符编码生成字符串  
	       return new String(bs, newCharset);  
	      }  
	      return null;  
	     }
}
